package io.mvvm.netty.codec.handler;

import io.mvvm.netty.codec.entity.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

/**
 * @program: Netty
 * @description: 编解码器
 * @author: 潘
 * @create: 2021-05-16 21:25
 **/
@ChannelHandler.Sharable
public class MessageCodec extends ByteToMessageCodec<Message> {

    @Override
    public void encode(ChannelHandlerContext ctx, Message msg, ByteBuf out) throws Exception {
        // 1. 魔数，4字节
        out.writeBytes(new byte[]{1, 2, 3, 4});
        // 2. 版本，1字节
        out.writeByte(1);
        // 3. 序列化算法(0:jdk, 1:json)，1字节
        out.writeByte(0);
        // 4. 指令类型，1字节
        out.writeByte(msg.getMessageType());
        // 5. 请求序号，4个字节
        out.writeInt(msg.getSequenceId());
        // 无意义，对齐填充，保持2的倍数
        out.writeByte(0xff);
        // 6. 获取内容的字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(msg);
        byte[] bytes = bos.toByteArray();
        // 7. 长度，4字节
        out.writeInt(bytes.length);
        // 8. 写入内容
        out.writeBytes(bytes);
    }

    @Override
    public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        // 1. 魔数，4字节
        int magicNum = in.readInt();
        // 2. 版本，1字节
        byte version = in.readByte();
        // 3. 序列化算法(0:jdk, 1:json)，1字节
        byte serializerAlgorithm = in.readByte();
        // 4. 指令类型，1字节
        byte messageType = in.readByte();
        // 5. 请求序号，4个字节
        int sequenceId = in.readInt();
        // 无意义，对齐填充，保持2的倍数
        in.readByte();
        // 6. 长度，4字节
        int length = in.readInt();
        // 7. 读取内容
        byte[] bytes = new byte[length];
        // 缓冲区，开始，结束
        in.readBytes(bytes, 0, length);
        ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Message message = (Message) stream.readObject();

        System.out.println(magicNum + "," + version + "," + length);
        out.add(message);
    }


}
